package phoneregistration.controller;

import java.util.HashSet;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import phoneregistration.controller.converter.PhoneConverter;
import phoneregistration.controller.model.PhoneModel;
import phoneregistration.domain.Phone;

import phoneregistration.service.PhoneService;

@Controller
@RequestMapping("/phone")
public class PhoneController {

    private final PhoneService service;
    private final PhoneConverter converter;

    @Autowired
    public PhoneController(PhoneService service, PhoneConverter converter) {
        this.service = service;
        this.converter = converter;
    }

    @RequestMapping(value="/{id}", method = RequestMethod.GET)
    public @ResponseBody PhoneModel findOne(@PathVariable("id") String id) {
        Assert.notNull(id);
        return converter.convertEntityToModel(service.findOne(id));
    }
    
    @RequestMapping(value="/", method = RequestMethod.GET)
    public @ResponseBody Set<PhoneModel> findAll() {
        Set<PhoneModel> models = new HashSet<PhoneModel>();
        for (Phone entity : service.findAll()) {
            models.add(converter.convertEntityToModel(entity));
        }
        return models;
    }
    
    @RequestMapping(value="/", method = RequestMethod.POST)
    public @ResponseBody PhoneModel create(@RequestBody PhoneModel model) {
        Assert.notNull(model);
        return save(model);
    }
    
    @RequestMapping(value="/{number}", method = RequestMethod.PUT)
    public @ResponseBody PhoneModel update(@PathVariable("number") String number, @RequestBody PhoneModel model) {
        Assert.notNull(number);
        Assert.notNull(model);
        model.setNumber(number);
        return save(model);
    }
    
    public PhoneModel save(PhoneModel model) {
        return converter.convertEntityToModel(service.save(converter.convertModelToEntity(model)));
    }

    @RequestMapping(value="/{id}", method = RequestMethod.DELETE)
    public void delete(@PathVariable("id") String id) {
        Assert.notNull(id);
        service.delete(id);
    }
    
}
